//
//  WebsocketManager.swift
//  CarHailingDriver
//
//  Created by guoliang.zhu on 2019/8/8.
//  Copyright © 2019 iOS-team. All rights reserved.
//

import Foundation
import Starscream

class KTWebsocketManager: NSObject {
    
    public static let `default` = KTWebsocketManager()
    var socket: WebSocket?
    /// 定时器
    private var timer: Timer?
    var isConnected = false
    private var socketConnected = false
    private var needConnect = false
    
    /// 位置上报socket
    /// - Parameter driverCode: 司机ID
    /// - Parameter cityCode: 城市编码
    @discardableResult
    public func initData() -> Self {
//        let socket = WebSocket(request: URLRequest(url: URL(string: socketUrl)!))
        //https://echo.websocket.org
        
//        {
//          "sub": "market.btcusdt.detail",
//          "id": "id1"
//        }
//        websocket  访问地址 ：  wss://api.huobi.pro/ws
//        订阅主题：
//        {
//          "sub": "market.btcusdt.detail",
//          "id": "id1"
//        }
//"ws://test.rent.wm-getngo.com:8080" + "/wm/lbs?driverCode=" + "1000001" + "&cityCode=" + "B10000001"
        var socketUrl = "wss://api.huobi.pro" + "/ws?sub=market.btcusdt.detail&id=id1"
//        socketUrl = "ws://test.rent.wm-getngo.com:8080" + "/wm/lbs?driverCode=" + "1000001" + "&cityCode=" + "B10000001"
        var request = URLRequest(url: URL(string: socketUrl)!)
        request.timeoutInterval = 5
        let socket = WebSocket(request: request)
        
        socket.delegate = self
        socket.connect()
        self.socket = socket
        return self
    }
    
    
    @discardableResult
    public func connect() -> Self{
        needConnect = true
        if let s = socket {
            s.connect()
        }
        return self
    }
    
    @discardableResult
    public func close() -> Self{
        guard (socket != nil) else { return self}
//        guard socket!.isConnected else { return self }
        needConnect = false
        socket!.disconnect()
        return self
    }
    
    public func sendMessage(_ msg: String) {
        guard (socket != nil) else { return }
        if socketConnected == false {
            self.connectAgain()
        }else {
            socket!.write(string: msg) {}
        }
    }

    // MARK: - 私有函数
    private override init() {
        super.init()
    }
    /// 发起重新连接
    private func connectAgain() {
        if self.needConnect {
            DLog("socket重新连接")
            self.socket?.connect()
        }
    }
}

extension KTWebsocketManager : WebSocketDelegate {
    func didReceive(event: WebSocketEvent, client: WebSocket) {
        switch event {
        case .connected(let headers):
            isConnected = true
            print("websocket is connected: \(headers)")
        case .disconnected(let reason, let code):
            isConnected = false
            print("websocket is disconnected: \(reason) with code: \(code)")
        case .text(let string):
            print("Received text: \(string)")
        case .binary(let data):
            print("Received data: \(data.count)")
        case .ping(_):
            break
        case .pong(_):
            break
        case .viablityChanged(_):
            break
        case .reconnectSuggested(_):
            break
        case .cancelled:
            isConnected = false
        case .error(let error):
            isConnected = false
            handleError(error)
        }
        
    }
    func handleError(_ error: Error?) {
        if let e = error as? WSError {
            print("websocket encountered an error: \(e.message)")
        } else if let e = error {
            print("websocket encountered an error: \(e.localizedDescription)")
        } else {
            print("websocket encountered an error")
        }
    }
    func websocketDidConnect(socket: WebSocketClient) {
        DLog("websocket连接成功")
        socketConnected = true
    }
    
    func websocketDidDisconnect(socket: WebSocketClient, error: Error?) {
        DLog("websocket连接失败\(String(describing: error))")
        socketConnected = false
    }
    
    func websocketDidReceiveMessage(socket: WebSocketClient, text: String) {
        
    }
    
    func websocketDidReceiveData(socket: WebSocketClient, data: Data) {
        
    }
}



